﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace LOLHelper.utils
{
    class HttpUtil
    {
        public static string password = "";
        public static string port = "";

        private static string authorize = "";
        private static string username = "riot";
        public static string basicUrl = "https://127.0.0.1";

        private static void Init()
        {
            if (password == "" || port == "")
            {
                throw new Exception("password 或 port 不能为空");
            }

            authorize = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
            basicUrl = "https://127.0.0.1:" + port;
        }

        /// <summary>
        /// 发送请求，数据为json
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static String HttpRequset(String url, CookieContainer cookieContainer = null, String data = null,
            String method = "GET", int timeout = 3000)
        {
            if (authorize == "" || basicUrl == "")
            {
                Init();
            }
            
            try
            {
                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;

                response = SendRequest(url, cookieContainer, data, method, timeout);
                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        break;

                    default:
                        response.Close();
                        throw new Exception("向服务器发送请求失败");
                }

                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));

                srcString = reader.ReadToEnd();

                reader.Close();
                response.Close();

                return srcString;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="data"></param>
        /// <param name="method"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private static HttpWebResponse SendRequest(String url, CookieContainer cookieContainer = null, String data = null,
            String method = "GET", int timeout = 3000)
        {
            url = basicUrl + url;
            
            HttpWebRequest request = null;

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                    ServicePointManager.ServerCertificateValidationCallback =
                        new RemoteCertificateValidationCallback(CheckValidationResult);
                    request.ProtocolVersion = HttpVersion.Version11;

                    // 这里设置了协议类型。
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType) (SecurityProtocolTypes.Ssl3 |
                        SecurityProtocolTypes.Tls | SecurityProtocolTypes.Tls11 | SecurityProtocolTypes.Tls12);
                    request.KeepAlive = false;
                    ServicePointManager.CheckCertificateRevocationList = true;
                    ServicePointManager.DefaultConnectionLimit = 100;
                    ServicePointManager.Expect100Continue = false;
                }
                else
                {
                    request = (HttpWebRequest) WebRequest.Create(url);
                }

                request.Method = method;
                request.ContentType = "application/json";
                request.Accept =
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
                request.AllowAutoRedirect = true;
                request.UserAgent =
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36";
                request.Timeout = timeout;
                request.Headers.Add("Authorization", "Basic " + authorize);

                if (cookieContainer != null)
                    request.CookieContainer = cookieContainer;

                if (data != null && data.Equals("") == false)
                {
                    byte[] stream = Encoding.UTF8.GetBytes(data);

                    Stream newStream = request.GetRequestStream();
                    newStream.Write(stream, 0, stream.Length);
                    newStream.Close();
                }

                //获取网页响应结果
                HttpWebResponse response;
                response = request.GetResponse() as HttpWebResponse;
                return response;
        }
        
        /// <summary>
        /// this
        ///
        ///d
        /// 获得响应中的图片
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static Image GetHeroAvatar(string url)
        {
            var httpWebResponse = SendRequest(url);
            return Image.FromStream(httpWebResponse.GetResponseStream() ?? throw new InvalidOperationException());
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,
            SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

        public enum SecurityProtocolTypes
        {
            Ssl3 = 0x30,
            Tls = 0xc0,
            Tls11 = 0x300,
            Tls12 = 0xc00
        }
    }
}